<template>
	<view class="main">
		<!-- 公共头部 -->
		<headerPublic style="position: fixed;" title="申请会议室" />
		<van-form class="form-box outbottom">
			<van-cell-group inset>
				<view class="form-title">
					<van-field v-model="form.flSubject" required label="会议标题：" placeholder="请输入会议标题" label-align="top"
						:rules="[{ required: true }]" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.flCreateDept" required readonly label="承办部门" :rules="[{ required: true }]" />
					<van-field v-model="form.flCreateDate" required readonly label="申请日期" :rules="[{ required: true }]" />
					<van-field v-model="form.flCreator" required readonly label="承办人" :rules="[{ required: true }]" />
					<van-field v-model="form.flCreatorPhone" label="联系电话" :rules="[{ required: true }]" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.startTime" required is-link readonly name="datePicker" label="会议开始时间"
						placeholder="请选择" @click="openPicker(0)" />
					<van-field v-model="form.endTime" required is-link readonly name="datePicker" label="会议结束时间" placeholder="请选择"
						@click="openPicker(1)" />
					<van-field v-model="form.meetPlace" required is-link readonly name="picker" label="会议室" placeholder="请选择"
						@click="goToSelect" />
					<van-field v-model="form.meetingNum" required label="参会人数" :rules="[{ required: true }]" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<view>
					<van-field v-model="form.remark" label="备注" placeholder="请输入备注" />
				</view>
			</van-cell-group>
			<van-cell-group inset style="margin-top: 10px;">
				<!-- <van-uploader class="uploader" :after-read="afterRead" :delete='beforeDelete' v-model="fileList" multiple
					accept=".pdf,.doc,.docx,image/*">
					<van-field is-link readonly label="附件" />
				</van-uploader> -->
				<view class="frct">
					<view class="fr-colum">
						<view class="fr-row fr-lable fr-2 fr-2-line">
							<text>附件</text>
							<uv-upload :fileList="fileList" name="FJ" multiple maxCount="6" :use-before-read="true"
								@beforeRead="beforeFileRead" @afterRead="afterRead" style="flex: none" accept="file"
								:file-ext-list="['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt']">
								<text class="c1">+添加</text>
							</uv-upload>
						</view>
						<view class="fiellist">
							<view class="fr-row flieit" v-for="(file, index) in fileList" :key="index">
								<text class="tname">{{ file.fileName }}</text>
								<text class="tsize">{{ file.fileSize }}MB</text>
								<uv-icon name="close" color="#2D75D7" size="14" @click="deleteFile(index)"></uv-icon>
							</view>
						</view>
					</view>
				</view>

			</van-cell-group>
			<view class="footer">
				<van-button block color="#2D75D7" @click="onSubmit(1)">
					提交
				</van-button>
			</view>
		</van-form>
		<van-popup v-model:show="showPicker" position="bottom">
			<van-datetime-picker v-model="currentDate" type="datetime" :title="pickerTitle" :min-date="minDate"
				@confirm="onConfirm" />
		</van-popup>
	</view>
</template>

<script>
	import {
		getLoginUserInfo,
		hyapSave,
		uploadFtpFile,
		roomList
	} from '../../../api'
	import {
		parseTime
	} from '../../../utils/format'
	import {
		getCookie
	} from '../../../utils/js-cookie'
	import {
		getRequestUrl
	} from '@/utils/request.js'
	export default {
		data() {
			return {
				form: {
					status: 1,
					fileIdStr: ""
				},
				showPicker: false,
				minDate: new Date(),
				pickerTitle: '',
				currentDate: '',
				fileList: [],
				// 允许的文件类型
				allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt'],
				// 单个文件最大大小 (10MB)
				maxSingleSize: 10 * 1024 * 1024,
				// 总文件最大大小 (50MB)
				maxTotalSize: 50 * 1024 * 1024,
				// 上传中状态
				uploading: false,
				// 当前总大小
				totalSize: 0,
				uploadErrors: []
			}
		},
		onLoad(e) {
			if (e.meetName) {
				const data = uni.getStorageSync('applyMeetingData')
				this.fileList = uni.getStorageSync('fileList')
				this.form = {
					...data
				}
				this.form.meetPlace = e.meetName
				this.form.meetingId = e.meetingId
			}
			if (e.sTime) {
				this.form.startTime = this.form.endTime = e.sTime
			}
			this.init()
		},
		methods: {
			init() {
				this.form.flCreateDate = parseTime(new Date())
				const userInfo = JSON.parse(getCookie('userInfo'))
				// console.log(userInfo);
				this.form.flCreateDept = userInfo.deptName
				this.form.flCreateDeptId = userInfo.deptId
				this.form.flCreator = userInfo.personName
				this.form.flCreatorId = userInfo.personId
				this.form.flCreatorPhone = userInfo.personMobile
			},
			onSubmit(type) {
				console.log('submit', this.form, type)
				uni.removeStorageSync('applyMeetingData')
				uni.removeStorageSync('fileList')
				this.form.status = 1
				if (!this.form.flSubject) {
					uni.showToast({
						title: '请输入会议标题',
						icon: 'error'
					})
					return
				}
				if (!this.form.meetingNum) {
					uni.showToast({
						title: '请输入参会人数',
						icon: 'error'
					})
					return
				}
				console.log(1111111)
				roomList({
					beginTimeConditionChoose: this.form.startTime,
					endTimeConditionChoose: this.form.endTime,
					status: 1,
					id: this.form.meetingId
				}).then(res => {
					if(res.data.rows.length == 0){
						hyapSave(this.form).then(res => {
							// console.log('res', res)
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
						
							this.form.meetPlace = ''
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/meeting/mine/list'
								})
							}, 800)
						})
						return 
					}
					if(res.data.rows[0].isOccupy == '0'){
						hyapSave(this.form).then(res => {
							// console.log('res', res)
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
						
							this.form.meetPlace = ''
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/meeting/mine/list'
								})
							}, 800)
						})
					}else{
						uni.showToast({
							title: '会议室已被占用',
							icon: 'error'
						})
					}
				})

			},
			openPicker(type) {
				if (type == 0) {
					this.pickerTitle = '开始时间'
				} else if (type == 1) {
					this.pickerTitle = '结束时间'
				}
				this.showPicker = true
			},
			onConfirm() {
				if (this.pickerTitle.includes('开始')) {
					// console.log('开始', this.currentDate, parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}'))
					this.minDate = this.currentDate
					this.form.startTime = parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}')
				} else if (this.pickerTitle.includes('结束')) {
					// console.log('结束', this.currentDate, parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}'))
					this.form.endTime = parseTime(this.currentDate, '{y}-{m}-{d} {h}:{i}')
				}
				this.showPicker = false
			},

			goToSelect() {
				if (this.form.startTime && this.form.endTime) {
					uni.setStorageSync('applyMeetingData', this.form)
					uni.setStorageSync('fileList', this.fileList)
					uni.navigateTo({
						url: `/pages/meeting/apply/select?beginTimeConditionChoose=${this.form.startTime}&endTimeConditionChoose=${this.form.endTime}`
					})
				} else {
					uni.showToast({
						title: '请选择开始与结束时间',
						icon: 'none'
					})
				}
			},
			// J计算文件大小
			FileSize() {
				this.totalSize = 0;
				this.totalSize = this.fileList.reduce((sum, file) => {
					return sum + (file.fileRealSize || 0);
				}, 0);
				// this.form.busiAttachIds = this.fileList && this.fileList.length > 0 ? this.fileList.map((file) =>
				// 	file.id).join() : null;
			},
			// 上传前文件类型检查
			beforeFileRead(file) {
				this.FileSize();
				const files = Array.isArray(file.file) ? file.file : [file];

				let isValid = true;
				files.forEach((f) => {
					// 检查文件类型
					const ext = this.getFileExtension(f.name || f.url).toLowerCase();
					// console.log(files, ext);
					if (!this.allowedExtensions.includes(ext)) {
						uni.showToast({
							title: `不支持的文件类型: ${ext}`,
							icon: 'none'
						});
						isValid = false;
						return;
					}

					// 检查单个文件大小
					if (f.size > this.maxSingleSize) {
						uni.showToast({
							title: '单个文件大小不能超过10MB',
							icon: 'none'
						});
						isValid = false;
						return;
					}

					// 检查总大小
					const newTotalSize = this.totalSize + f.size;
					if (newTotalSize > this.maxTotalSize) {
						uni.showToast({
							title: '文件总大小不能超过50MB',
							icon: 'none'
						});
						isValid = false;
					}
				});
				return isValid;
			},
			// 获取文件扩展名
			getFileExtension(filename) {
				if (!filename) return '';
				return filename.split('.').pop().toLowerCase();
			},
			// 删除文件
			deleteFile(index) {
				this.fileList.splice(index, 1);
				this.FileSize()
			},
			async afterRead(event) {
				// console.log(22,event);
				const files = Array.isArray(event.file) ? event.file : [event.file];
				this.uploading = true;
				this.uploadErrors = [];
				try {
					// 并行处理所有文件上传，但按顺序收集结果
					const results = await Promise.allSettled(files.map((file, index) => this.uploadFilePromise(file.url,
						index)));
					let fileIdArray = []

					console.log(44, results);

					// 处理成功的上传结果
					results.forEach((result, index) => {
						if (result.status === 'fulfilled') {
							if (result.value) {
								this.fileList.push(result.value);
								fileIdArray.push(result.value.id)
								this.form.fileIdStr = fileIdArray.join(',')
								this.FileSize();
							}
						} else {
							this.uploadErrors.push({
								index,
								error: result.reason
							});
						}
					});

					if (this.uploadErrors.length > 0) {
						uni.showToast({
							title: `部分文件上传失败(${this.uploadErrors.length}/${files.length})`,
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '全部文件上传成功',
							icon: 'none',
							duration: 1500
						});
					}
				} catch (error) {
					console.error('文件上传过程中发生错误:', error);
					uni.showToast({
						title: '上传过程中发生错误',
						icon: 'none'
					});
				} finally {
					this.uploading = false;
				}
			},
			uploadFilePromise(url, fileIndex) {
				return new Promise((resolve, reject) => {
					const base_url = uni.getStorageSync('apiUrl') ? uni.getStorageSync('apiUrl') : '/api';
					uni.uploadFile({
						url: getRequestUrl() + '/app/common/uploadFtpFile',
						filePath: url,
						name: 'file',
						header: {
							'ECWEB-JWTSSO-TOKEN': uni.getStorageSync('token')
						},
						success: (res) => {
							try {
								// 直接解析响应数据
								const responseData = JSON.parse(res.data).data
								console.log(11, JSON.parse(res.data).data);
								console.log(22, responseData);
								if (responseData) {
									resolve(responseData);
								}
								// else {
								// 	reject(new Error('服务器返回数据格式错误'));
								// }
							} catch (parseError) {
								reject(parseError);
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.uploader {
		width: 100%;

		::v-deep .van-uploader__input-wrapper {
			width: 100%;
		}
	}

	.frct {
		margin-bottom: 0;
		padding: 16px;
		font-size: 14px;
		background: #fff;
		border-radius: 5px;
		display: flex;
		flex-direction: column;

		.fr-colum {
			display: flex;
			flex-direction: column;
			position: relative;
		}

		.fr-2 {
			color: #a5a5a5;
			font-weight: 400;
		}

		.fr-lable {
			color: #555555;
			padding-bottom: 11px;
			// font-weight: bold;
		}

		.fr-row {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.fiellist {
			padding: 14px 0;
			border-top: 1px solid #efefef;
		}
	}

	::v-deep .uv-upload__wrap__preview {
		display: none;
	}

	.main {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.form-box {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		padding-top: 10px;
		margin-bottom: 50rpx;
		border-bottom: 0;
		min-height: 0;
	}

	.form-title {
		::v-deep .van-cell {
			flex-direction: column;
		}

		::v-deep .van-field__body {
			border-bottom: 1px solid #efefef;
			margin-top: 10px;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		background-color: #fff;
		width: 95%;
		padding: 10px;
		display: flex;
		justify-content: center;

		::v-deep .van-button--block {
			width: 100%;
		}
	}

	.uploader {
		width: 100%;

		::v-deep .van-uploader__input-wrapper {
			width: 100%;
		}
	}

	.outbottom {
		margin-top: 88rpx;
	}
</style>